package src.dual_pointers;

import java.util.HashMap;
import java.util.Map;

/**
 * @author starsea
 * @date 2024-08-25 20:43
 */

public class Test09 {
    public static void main(String[] args) {
        String s = "ADOBECODEBANC";String t = "ABC";
        String v=minWindow(s,t);
        //String[] words = {"foo", "bar"};
        //String c=reverseMessage(s);
    }
    public static String minWindow(String s, String t) {
        if(t.length()>s.length())
        {
            return new String();
        }
        int a=0;
        int b=0;
        int max=0x3f3f3f;
        int left=0;
        int right=0;
        Map<Character,Integer>map=new HashMap<>();
        Map<Character,Integer> map1=new HashMap<>();
        for(int i=0;i<t.length();i++)
        {
            if(!map.containsKey(t.charAt(i)))
            {
                map.put(t.charAt(i),1);
            }else {
                map.put(t.charAt(i),map.get(t.charAt(i))+1);
            }
        }
        while (right<s.length())
        {
            while (right<s.length() && !isSubset(map,map1))
            {
                if(!map1.containsKey(s.charAt(right)))
                {
                    map1.put(s.charAt(right),1);
                }else {
                    map1.put(s.charAt(right),map1.get(s.charAt(right))+1);
                }
                right++;
            }
            while (isSubset(map,map1))
            {
                if(isSubset(map,map1))
                {
                    if(max>right-left)
                    {
                        max=right-left;
                        a=left;
                        b=right;
                    }
                }
                if(map1.get(s.charAt(left))==1)
                {
                    map1.remove(s.charAt(left));
                }else{
                    map1.put(s.charAt(left),map1.get(s.charAt(left))-1);
                }
                left++;
            }
        }
        return s.substring(a,b);

    }


    public static boolean isSubset(Map<Character, Integer> map, Map<Character, Integer> map1) {
        for(Map.Entry<Character,Integer> entry: map.entrySet()){
            if(!map1.containsKey(entry.getKey()) || map1.get(entry.getKey())<entry.getValue())
            {
                return false;
            }
        }
        return true;
    }
    public static String reverseMessage(String message) {
        message=message.trim();
        String[] arr=message.split(" ");
        StringBuffer buffer=new StringBuffer();
        for(int i=arr.length-1;i>=0;i--)
        {
            if("".equals(arr[i])){continue;}
            buffer.append(arr[i]).append(" ");
        }
        message=buffer.toString().trim();
        return message;

    }

}
